/*
 * Copyright (c) 2010-2011 Plugger Antonio Begue Ponce. All Rights Reserved.
 *
 * This file is part of Plugger Framework.
 *
 *  Plugger Framework is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License version 3 as published by
 *  the Free Software Foundation.
 *
 *  Plugger Framework is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Plugger Framework.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.plugger.ui.base;

import com.jgoodies.binding.beans.Model;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * An abstract class that represent the controller of a view.<BR/>
 * Can be used as a Java Beans.
 *
 * @author "Antonio Begue"
 * @version $Revision: 1.0 $
 */
public abstract class ViewModelBase extends Model implements IViewModel {
    private IView view;
    private DelegateAction cancelAction;

    /**
     * A basic ViewModelBase constructor, creates a null view.
     */
    public ViewModelBase() {
        this(null);
    }

    /**
     * A ViewModelBase constructor that receive a view.
     * @param view The IView to be controlled.
     */
    public ViewModelBase(IView view) {
        this.view = view;
        cancelAction = new DelegateAction("Cancel", new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                cancelActionHandler(e);
            }
        });
    }

    public void cancelActionHandler(ActionEvent e) {
        this.closeView();
    }

    protected abstract void onCloseView();

    public void closeView() {
        onCloseView();
        if (this.getView() != null) {
            this.getView().close();
        }
    }

    /**
     * The cancelAction execute the abstract function onCloseView and then execute close on the view.
     * @return the cancelAction
     */
    public DelegateAction getCancelAction() {
        return cancelAction;
    }

    public DelegateAction getCancelAction(String title) {
        cancelAction.setTitle(title);
        return cancelAction;
    }

    /**
     * @return the view
     */
    public IView getView() {
        return view;
    }
}
